<!DOCTYPE html>
<html>
	<head>
		<title>商品修改</title>
		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
		<meta name="viewport" content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no" />
		<!-- Vue 3 和 Element Plus 资源 -->
		<link rel="stylesheet" href="https://unpkg.com/element-plus@2.3.0/dist/index.css">
		<link rel="stylesheet" href="../../static/sa.css">
		<script src="https://unpkg.com/vue@3.3.0/dist/vue.global.js"></script>
		<script src="https://unpkg.com/element-plus@2.3.0/dist/index.full.js"></script>
		<script src="https://unpkg.com/jquery@3.4.1/dist/jquery.js"></script>
		<script src="https://www.layuicdn.com/layer-v3.1.1/layer.js"></script>
		<script>
			// 更强的 sa.js 错误修复
			window.sa = window.sa || {};

			// 捕获并忽略 sa.js 的错误
			window.addEventListener('error', function(e) {
				if (e.filename && e.filename.includes('sa.js')) {
					console.warn('sa.js error caught and ignored:', e.message);
					e.preventDefault();
					return false;
				}
			});
		</script>
		<script src="../../static/sa.js"></script>
		<script>
			// 确保 sa 对象的基本方法存在
			window.sa = window.sa || {};
			window.sa.p = window.sa.p || function(key) {
				const urlParams = new URLSearchParams(window.location.search);
				return urlParams.get(key);
			};
			window.sa.closeCurrIframe = window.sa.closeCurrIframe || function() {
				if (window.parent && window.parent !== window) {
					window.parent.postMessage('closeIframe', '*');
				}
			};
		</script>
		<style type="text/css">
			.form-container {
				padding: 20px;
				background: #fff;
				border-radius: 4px;
				box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
			}
			.form-header {
				margin-bottom: 30px;
				border-bottom: 1px solid #eee;
				padding-bottom: 15px;
			}
			.form-header h2 {
				margin: 0;
				color: #303133;
			}
			.image-uploader {
				border: 1px dashed #d9d9d9;
				border-radius: 6px;
				cursor: pointer;
				position: relative;
				overflow: hidden;
				width: 178px;
				height: 178px;
			}
			.image-uploader:hover {
				border-color: #409EFF;
			}
			.image-uploader-icon {
				font-size: 28px;
				color: #8c939d;
				width: 178px;
				height: 178px;
				line-height: 178px;
				text-align: center;
			}
			.product-image {
				width: 178px;
				height: 178px;
				display: block;
			}
			.editor-container {
				margin-top: 10px;
				min-height: 300px;
			}
		</style>
	</head>
	<body>
		<div class="vue-box">
			<div class="s-body">
				<div class="form-container">
					<div class="form-header">
						<h2>修改商品</h2>
					</div>
					<div v-loading="loading" element-loading-text="加载中...">
						<el-form :model="m" :rules="rules" ref="productFormRef" label-width="100px">
						<el-form-item label="商品名称" prop="name">
							<el-input v-model="m.name" placeholder="请输入商品名称"></el-input>
						</el-form-item>
						<el-form-item label="商品分类" prop="categoryId">
							<el-select v-model="m.categoryId" placeholder="请选择商品分类">
								<el-option
									v-for="item in categories"
									:key="item.id"
									:label="item.name"
									:value="item.id">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item label="商品图片" prop="image">
							<el-upload
								class="image-uploader"
								action="/upload"
								:show-file-list="false"
								:on-success="handleImageSuccess"
								:before-upload="beforeImageUpload">
								<img v-if="m.image" :src="imagePreviewUrl + m.image" class="product-image">
								<i v-else class="el-icon-plus image-uploader-icon"></i>
							</el-upload>
						</el-form-item>
						<el-form-item label="商品价格" prop="price">
							<el-input-number 
								v-model="m.price" 
								:precision="2" 
								:step="0.1" 
								:min="0"
								controls-position="right"
								placeholder="请输入商品价格">
							</el-input-number>
						</el-form-item>
						<el-form-item label="库存数量" prop="stock">
							<el-input-number 
								v-model="m.stock" 
								:min="0" 
								controls-position="right"
								placeholder="请输入库存数量">
							</el-input-number>
						</el-form-item>
						<el-form-item label="商品状态" prop="status">
							<el-switch
								v-model="m.status"
								:active-value="1"
								:inactive-value="0"
								active-text="上架"
								inactive-text="下架">
							</el-switch>
						</el-form-item>
						<el-form-item label="商品描述" prop="description">
							<el-input 
								type="textarea" 
								v-model="m.description" 
								:rows="4"
								placeholder="请输入商品描述">
							</el-input>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="ok()" :loading="loading">保存修改</el-button>
							<el-button @click="sa.closeCurrIframe()">取消</el-button>
						</el-form-item>
					</el-form>
					</div>
				</div>
			</div>
		</div>
		<script src="./moke-data.js"></script>
        <script>
			const { createApp, ref, reactive, computed, onMounted } = Vue;
			const { ElMessage } = ElementPlus;

			const app = createApp({
				setup() {
					// 响应式数据
					const id = ref(sa.p('id'));
					const m = ref({
						id: null,
						name: '',
						description: '',
						price: 0,
						stock: 0,
						status: 1,
						categoryId: null,
						image: null
					});
					const loading = ref(true); // 初始为加载状态
					const categories = ref([]);
					const imagePreviewUrl = ref('http://8.134.184.130:8008/images/');
					const productFormRef = ref(null);

					// 表单验证规则
					const rules = reactive({
						name: [
							{ required: true, message: '请输入商品名称', trigger: 'blur' },
							{ min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
						],
						categoryId: [
							{ required: true, message: '请选择商品分类', trigger: 'change' }
						],
						image: [
							{ required: true, message: '请上传商品图片', trigger: 'change' }
						],
						price: [
							{ required: true, message: '请输入商品价格', trigger: 'blur' }
						],
						stock: [
							{ required: true, message: '请输入库存数量', trigger: 'blur' }
						],
						description: [
							{ required: true, message: '请输入商品描述', trigger: 'blur' }
						]
					});
					
					// 图片上传前的验证
					const beforeImageUpload = (file) => {
						const isImage = file.type.indexOf('image/') === 0;
						const isLt2M = file.size / 1024 / 1024 < 2;

						if (!isImage) {
							ElMessage.error('上传文件只能是图片格式!');
							return false;
						}
						if (!isLt2M) {
							ElMessage.error('上传图片大小不能超过 2MB!');
							return false;
						}
						return true;
					};

					// 图片上传成功的回调
					const handleImageSuccess = (res, file) => {
						m.value.image = res.data.url;
					};

					// 映射后端数据到前端表单格式
					const mapProductData = (data) => {
						return {
							id: data.id,
							name: data.name,
							description: data.description,
							price: data.price,
							stock: data.stock,
							// 状态字段映射：isActive -> status
							status: data.isActive ? 1 : 0,
							// 分类ID处理
							categoryId: data.categoryId,
							// 图片处理：从images数组中取主图
							image: data.images && data.images.length > 0 ? data.images[0].image_url : null
						};
					};
					// 提交修改
					const ok = async () => {
						try {
							// Vue 3 表单验证
							if (productFormRef.value) {
								const valid = await productFormRef.value.validate();
								if (!valid) return;
							}

							loading.value = true;

							// 将前端数据格式转换为后端期望的格式
							const submitData = {
								id: m.value.id,
								name: m.value.name,
								description: m.value.description,
								price: m.value.price,
								stock: m.value.stock,
								// 状态字段映射：status -> isActive
								isActive: m.value.status === 1,
								categoryId: m.value.categoryId,
								// 如果有图片，构造images数组格式
								images: m.value.image ? [{
									image_url: m.value.image,
									is_main: true
								}] : []
							};

							// 使用 fetch API
							const response = await fetch('http://localhost:8080/product/update', {
								method: 'POST',
								headers: {
									'Content-Type': 'application/json',
								},
								body: JSON.stringify(submitData)
							});

							const res = await response.json();
							loading.value = false;

							if (res.code === 200) {
								ElMessage.success('修改成功');
								parent.app.f5();
								sa.closeCurrIframe();
							} else {
								ElMessage.error(res.msg || res.message || '修改失败');
							}
						} catch (error) {
							loading.value = false;
							console.error('修改失败:', error);
							ElMessage.error('修改失败，请重试');
						}
					};

					// 加载商品分类
					const loadCategories = async () => {
						try {
							console.log('开始加载商品分类...');
							const response = await fetch('http://localhost:8080/coupon/listCoupon', {
								method: 'GET',
								headers: {
									'Content-Type': 'application/json',
								}
							});

							const res = await response.json();
							console.log('分类数据响应:', res);

							if (res && res.code === 200 && res.data) {
								// 假设返回的数据格式是数组，每个元素有 id 和 name 字段
								categories.value = Array.isArray(res.data) ? res.data : [];
								console.log('分类数据加载成功:', categories.value);
							} else {
								console.warn('分类数据加载失败:', res);
								categories.value = [];
							}
						} catch (error) {
							console.error('加载分类数据失败:', error);
							categories.value = [];
						}
					};

					// 生命周期钩子
					onMounted(async () => {
						// 并行加载分类数据
						loadCategories();
						if (!id.value) {
							ElMessage.error('缺少商品ID参数');
							return;
						}

						console.log('准备加载商品ID:', id.value);



						// 加载商品数据
						const apiUrl = 'http://localhost:8080/product/getProductById?id=' + id.value;
						console.log('请求商品数据URL:', apiUrl);

						// 使用 fetch API 加载商品数据
						try {
							const response = await fetch(apiUrl, {
								method: 'GET',
								headers: {
									'Content-Type': 'application/json',
								}
							});

							const res = await response.json();
							console.log('商品数据响应:', res);

							// 更宽容的数据处理
							if (res && res.data) {
								// 如果返回的是数组，取第一个元素；如果是对象，直接使用
								if (Array.isArray(res.data)) {
									if (res.data.length > 0) {
										m.value = mapProductData(res.data[0]);
										console.log('加载商品数据成功:', m.value);
									} else {
										console.warn('商品数据为空数组，商品ID:', id.value);
										ElMessage.warning(`商品ID ${id.value} 不存在，请检查商品是否已被删除`);
										// 创建一个空的商品对象，让用户可以看到表单
										m.value = {
											id: id.value,
											name: '',
											description: '',
											price: 0,
											stock: 0,
											status: 1,
											categoryId: null,
											image: null
										};
									}
								} else {
									m.value = mapProductData(res.data);
									console.log('加载商品数据成功:', m.value);
								}
							} else if (res && res.code !== 200) {
								console.warn('接口返回错误:', res);
								ElMessage.warning('获取商品数据失败: ' + (res.msg || res.message || '未知错误'));
								// 不自动关闭，让用户看到错误信息
							} else {
								console.warn('接口返回数据格式异常:', res);
								ElMessage.warning('商品数据格式异常，请联系管理员');
								// 不自动关闭，让用户看到错误信息
							}

							// 无论成功还是失败，都停止加载状态
							loading.value = false;
						} catch (error) {
							console.error('加载商品数据失败:', error);
							ElMessage.error('网络请求失败，请检查网络连接');
							loading.value = false;
							// 不自动关闭，让用户看到错误信息
						}
					});

					// 返回模板中需要使用的数据和方法
					return {
						id,
						m,
						loading,
						categories,
						imagePreviewUrl,
						rules,
						productFormRef,
						beforeImageUpload,
						handleImageSuccess,
						mapProductData,
						loadCategories,
						ok
					};
				}
			});

			// 注册 Element Plus
			app.use(ElementPlus);

			// 挂载应用
			app.mount('.vue-box');
		</script>
	</body>
</html>